<?php
/**
 *（logic）移库订单明细（amazon同步数据至ERP）
 * os-in:sync-removal-od
 */
namespace App\Logic\OverSeasIn;

use App\Models\Amazon\AmazonReportCondition;
use App\Models\Amazon\FbaRemovalOrderDetail;
use App\Models\Basics\AmazonAccount;
use App\Models\Basics\SysPlatAccount;
use App\Models\OverSeasBa\RemovaleInventoryFNSku;
use App\Models\OverSeasBa\Warehouse;
use App\Models\OverSeasIn\RemovalePlan;
use App\Models\OverSeasIn\RemovaleOrderDetail;
use App\Models\Product\ProductAmazonSku;
use Illuminate\Support\Facades\DB;
class SyncRemovalOrderDetail
{
    public static function init(){

        $type = 'GET_FBA_FULFILLMENT_REMOVAL_ORDER_DETAIL_DATA';
        try{
            $date = AmazonReportCondition::getStartTime($type);
            if(!$date)die('日期设置错误！');
            DB::beginTransaction();

            //Amazon移库订单
            $re = FbaRemovalOrderDetail::query()
                ->where('order_type','Return')
                ->where('request_date','>=',$date)
                ->get();
            $existSku = [];
            $i = 0;
            $num = 500;
            while (true){
                if($re->isEmpty())break;
                $items = $re->splice($i,$num);
                foreach ($items as $item){
                    $key = $item->account_id.'-'.$item->sku.'-'.$item->fnsku;
                    if(!array_key_exists($key,$existSku)){
                        $account = SysPlatAccount::query()->find($item->account_id);
                        $countryIds = $account->account_country->pluck('country_id') ?? [];
                        $pas = ProductAmazonSku::query()
                            ->whereIn('country_id',$countryIds)
                            ->where('seller_sku',$item->sku)
                            ->first();
                        $existSku[$key] = $pas ? $pas->psku_id : null;
                    }
                    if(!$existSku[$key])continue;

                    //erp移库计划(验证订单)
                    $rp = RemovalePlan::query()
                        ->where('order_id',$item->order_id)
                        ->first();
                    if($rp){
                        $warehouse = Warehouse::getWarehouseById($rp->warehouse_id);
                        $warehouseId = $rp->warehouse_id;
                        $areaId = $warehouse->area_id;
                        $countryId = $warehouse->country_id;
                    }else{
                        $warehouseId = 0;
                        $areaId = 0;
                        $countryId = 0;
                    }

                    //erp移库订单
                    RemovaleOrderDetail::query()
                        ->updateOrCreate([
                                'account_id' => $item->account_id,
                                'order_id' => $item->order_id,
                                'seller_sku' => $item->sku,
                            ],[
                                'request_date' => $item->request_date,
                                'fnsku' => $item->fnsku,
                                'warehouse_id' => $warehouseId,
                                'area_id' => $areaId,
                                'country_id' => $countryId,
                                'psku_id' => $existSku[$key],
                                'requested_quantity' => $item->requested_quantity,
                                'cancelled_quantity' => $item->cancelled_quantity,
                                'disposed_quantity' => $item->disposed_quantity,
                                'shipped_quantity' => $item->shipped_quantity,
                                'in_process_quantity' => $item->in_process_quantity,
                        ]);
                    if($warehouseId > 0){
                        //海外仓移库库存
                        $inventory = RemovaleInventoryFNSku::query()
                            ->firstOrNew([
                                    'account_id' => $item->account_id,
                                    'warehouse_id' => $warehouseId,
                                    'fnsku' => $item->fnsku,
                                ],[
                                    'psku_id' => $existSku[$key],
                                ]
                            );
                        $inventory->transit += $item->shipped_quantity; //发运数量
                        $inventory->save();
                    }
                }
            }

            AmazonReportCondition::upStartTime($type, date('Y-m-d', time()));
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }
}
